﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GJK3DShape
{
    /// <summary>
    /// 顶点数组
    /// </summary>
    public Vector3[] ShapeVertices;

    /// <summary>
    /// 中心点位置
    /// </summary>
    public Vector3 Center;

    /// <summary>
    /// 网格名称
    /// </summary>
    public string MeshName;

    /// <summary>
    /// 移动组件
    /// </summary>
    public Transform TransformComp;

    public GJK3DShape(Transform tra, Mesh mesh)
    {
        if (mesh == null)
        {
            Debug.LogError("Mesh 对象为空");
            return;
        }
        ShapeVertices = new Vector3[mesh.vertices.Length];
        ShapeVertices = mesh.vertices;
        MeshName = mesh.name;
        Center = tra.position;
        TransformComp = tra;
    }

    /// <summary>
    /// 寻找当前方向最近的点
    /// </summary>
    /// <param name="direction"></param>
    public Vector3 Support(Vector3 direction)
    {
        if (ShapeVertices == null)
        {
            Debug.LogError(MeshName + ": 顶点数量为null！");
            return Vector3.zero;
        }
        Vector3 tempPoint = TransformComp.TransformPoint(ShapeVertices[0]);
        float maxValue = float.MinValue;
        for (int i = 0; i < ShapeVertices.Length; i++)
        {
            Vector3 worldPos = TransformComp.TransformPoint(ShapeVertices[i]);
            float value = Vector3.Dot(worldPos, direction);
            if (maxValue < value)
            {
                maxValue = value;
                tempPoint = worldPos;
            }
        }
        return tempPoint;
    }

    /// <summary>
    /// 显示调试信息
    /// </summary>
    public void DebugVertices()
    {
        for (int i = 0; i < ShapeVertices.Length; i++)
        {
            GameObject Sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            Sphere.transform.localScale = Vector3.one * 0.01f;
            Sphere.transform.position = ShapeVertices[i];
            Debug.Log("<color =green> x:" + ShapeVertices[i].x + " y :" + ShapeVertices[i].y + " z :" + ShapeVertices[i].z + "</color>");
        }
    }

    public Vector3 GetWordPos(Vector3 point)
    {
        return this.TransformComp.TransformPoint(point);
    }

    public void Destory()
    {

        TransformComp = null;
    }

}
